import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import CryptoJS from 'crypto-js'
import { useUserStore } from '@/store'
import { info, changeToken } from '@/api/login'
import { setUserInfo } from '@/utils/storage'
import router from './index'

NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, _from, next) => {
  NProgress.start()

  // 解决 iphone 跳转后页面不能到顶部的问题
  window.scrollTo(0, 0)

  const store = useUserStore()

  // 免密登录
  const pathParams: any = to.query

  if (pathParams.user && pathParams.pwd) {
    const key = CryptoJS.enc.Utf8.parse('AD42F6697B035B75')
    const srcs = CryptoJS.enc.Utf8.parse(pathParams.pwd)
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })

    await store.login({
      username: pathParams.user,
      password: encrypted.toString(),
      remember: true
    })
    if (to.name == 'Login') {
      router.replace({ path: '/home' })
    } else {
      const query = to.query
      delete query.user
      delete query.pwd
      router.replace({ path: to.path, query })
    }
    next()
  }
  // 通过code获取token,并获取用户信息(对接即墨山东通)
  if (pathParams.code) {
    const { data: token } = await changeToken(pathParams.code)
    store.setToken(token)
    const { data: userInfo } = await info()
    store.setUserInfo(userInfo)
    setUserInfo({
      token: pathParams.token,
      userInfo: userInfo
    })
    router.replace({ path: 'home' })
    next()
  }

  if (!store.isLogin && to.path !== '/login') {
    await store.logout()
    next({ path: '/login', replace: true })
  } else {
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

export default router
